<template>
	<div class="admin">
		<div class="admin-title">
			{{ t("studentInfo.title") }}
			<el-button type="primary" @click="showAddDialog">{{ t("studentInfo.add") }}</el-button>
		</div>

		<CommonTable
			:table-data="tableData"
			:table-config="tableConfig"
			:table-loading="loading"
			:is-show-index="true"
		>
			<template #operations="{ row }">
				<el-button size="small" type="success" @click="handleEdit(row)">{{ t("studentInfo.edit") }}</el-button>
				<el-button size="small" type="danger" @click="handleDelete(row)">{{ t("studentInfo.delete") }}</el-button>
			</template>
		</CommonTable>

		<Pagination
			:background="true"
			:total="total"
			:current-page.sync="pageNum"
			:page-size.sync="pageSize"
			@pagination-change="paginationChange"
			class="pagination"
		/>

		<!-- 添加学员弹框 -->
		<el-dialog
			v-model="dialogVisible"
			:title="dialogTitle"
			width="500px"
			:before-close="handleClose"
		>
			<el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
				<el-form-item :label="t('studentInfo.form.name')" prop="nameC">
					<el-input v-model="formData.nameC" :placeholder="t('studentInfo.form.namePlaceholder')" />
				</el-form-item>

				<el-form-item :label="t('studentInfo.form.phone')" prop="mobile">
					<el-input v-model="formData.mobile" :placeholder="t('studentInfo.form.phonePlaceholder')" />
				</el-form-item>

				<el-form-item :label="t('studentInfo.form.gender')" prop="sex">
					<el-radio-group v-model="formData.sex">
						<el-radio :value="1">{{ t("studentInfo.genderOptions.male") }}</el-radio>
						<el-radio :value="0">{{ t("studentInfo.genderOptions.female") }}</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item :label="t('studentInfo.form.birthday')" prop="birthDate">
					<el-date-picker
						v-model="formData.birthDate"
						type="date"
						:placeholder="t('studentInfo.form.birthdayPlaceholder')"
						format="YYYY/MM/DD"
						value-format="YYYY-MM-DD"
						style="width: 100%"
					/>
				</el-form-item>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleCancel">{{ t("studentInfo.cancel") }}</el-button>
					<el-button type="primary" @click="handleSave">{{ t("studentInfo.save") }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { AddStudent, GetStudentList, RemoveStudent, UpdateStudent } from '~/apis/web';
import { userStore } from '~/composables/store/modules/user';

definePageMeta({
	title: '学员信息',
	en_title: 'Student Information',
	zh_hk_title: '營員資訊',
	ssr: true, // 必须为 true
	isTokenCheck: true,
});

const { t, locale } = useI18n();

const uStore = userStore();

// 分页
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);

// 弹框相关
const dialogVisible = ref(false);
const formRef = ref(null);
const formData = ref({
	id: undefined,
	nameC: '',
	mobile: '',
	sex: '',
	birthDate: '',
});

const dialogTitle = computed(() =>
	formData.value.id ? t("studentInfo.editTitle") : t("studentInfo.addTitle")
);

// 表单验证规则
const formRules = computed(() => ({
	nameC: [{ required: true, message: t("studentInfo.rules.name"), trigger: 'blur' }],
	mobile: [
		{ required: true, message: t("studentInfo.rules.phone"), trigger: 'blur' },
		{
			pattern: /^[+]?[\d\s\-\(\)]{7,20}$/,
			message: t("studentInfo.rules.phoneInvalid"),
			trigger: 'blur',
		},
	],
	sex: [{ required: true, message: t("studentInfo.rules.gender"), trigger: 'change' }],
	birthDate: [{ required: true, message: t("studentInfo.rules.birthday"), trigger: 'change' }],
}));

// 表格配置
const tableConfig = computed(() => [
	{ prop: 'nameC', label: t("studentInfo.table.name") },
	{ prop: 'mobile', label: t("studentInfo.table.phone") },
	{ prop: 'sexName', label: t("studentInfo.table.gender") },
	{ prop: 'birthDate', label: t("studentInfo.table.birthday") },
	{ prop: 'age', label: t("studentInfo.table.age") },
	{ prop: 'operations', label: t("studentInfo.table.actions"), slotName: 'operations' },
]);

// 数据（示例）
const tableData = ref([]);

const loading = ref(false);

const formatSex = sex => {
	const value = sex === undefined || sex === null ? '' : String(sex);
	if (value === '1') return t("studentInfo.genderOptions.male");
	if (value === '0') return t("studentInfo.genderOptions.female");
	return t("studentInfo.genderOptions.unknown");
};

const mapStudentList = (list = []) =>
	(list || []).map(item => ({
		...item,
		sexName: formatSex(item.sex),
	}));

// 显示添加学员弹框
const showAddDialog = () => {
	dialogVisible.value = true;
	resetForm();
};

// 重置表单
const resetForm = () => {
	formData.value = {
		id: undefined,
		nameC: '',
		mobile: '',
		sex: '',
		birthDate: '',
	};
	if (formRef.value) {
		formRef.value.clearValidate();
	}
};

// 关闭弹框
const handleClose = () => {
	dialogVisible.value = false;
	resetForm();
};

// 取消按钮
const handleCancel = () => {
	handleClose();
};

// 保存按钮
const handleSave = async () => {
	if (!formRef.value) return;
	try {
		await formRef.value.validate();
		// 计算年龄
		const age = new Date().getFullYear() - new Date(formData.value.birthDate).getFullYear();
		const isUpdate = Boolean(formData.value.id);
		// 添加到表格数据
		const newStudent = {
			...formData.value,
			age,
			userId: uStore.user.id,
		};
		delete newStudent.sexName;
		if (newStudent.id) {
			await UpdateStudent(newStudent);
		} else {
			await AddStudent(newStudent);
		}
		await loadData();
		// 关闭弹框
		handleClose();
		ElMessage.success(isUpdate ? t("studentInfo.messages.updateSuccess") : t("studentInfo.messages.addSuccess"));
	} catch (error) {
		console.log('表单验证失败:', error);
	}
};

const handleEdit = row => {
	formData.value = { ...row };
	dialogVisible.value = true;
};

const handleDelete = async row => {
	await RemoveStudent(row.id);
	await loadData();
	ElMessage.success(t("studentInfo.messages.deleteSuccess"));
};

const paginationChange = val => {
	pageNum.value = val.currentPage;
	pageSize.value = val.pageSize;
	loadData();
};

const loadData = async () => {
	if (loading.value) return;
	loading.value = true;
	try {
		const params = {
			pageNo: pageNum.value,
			pageSize: pageSize.value,
			userId: uStore.user.id,
		};
		const { data, code } = await GetStudentList(params);
		if (code === 0) {
			tableData.value = mapStudentList(data?.list || []);
			total.value = Number(data?.total) || 0;
		}
	} finally {
		loading.value = false;
	}
};

watch(
	() => locale.value,
	() => {
		tableData.value = mapStudentList(tableData.value);
	}
);

loadData();
</script>

<style scoped>
.admin-title {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
}

.pagination {
	margin-top: 20px;
	text-align: right;
}
</style>
